import {Component, OnInit} from '@angular/core';
import {Router, ActivatedRoute} from "@angular/router";
import {ResponseUtil} from "../../../../util/response-util";
import {PageSubject} from "../../../../util/page-subject";
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {MsgResult} from "../../../../models/msg-result";
import {FormGroup, FormBuilder, Validators} from "@angular/forms";
import {MsgConstants} from "../../../../constants/constants";
import {TreeUtil} from "../../../../util/tree-util";
import {Dictionary} from "../dictionary";
import {DictionarysService} from "../dictionarys.service";

declare var $;
@Component({
  selector: 'app-dictionary-update',
  templateUrl: './dictionary-update.component.html',
  styleUrls: ['./dictionary-update.component.css']
})
export class DictionaryUpdateComponent implements OnInit {
  id : string;
  pId:string;
  dic :Dictionary;

  dicForm: FormGroup;

  treeObj;
  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private fb: FormBuilder,
    private treeUtil: TreeUtil,
    private pageSubject : PageSubject,
    private responseUtil : ResponseUtil,
    private dialogService : OneDialogService,
    private dicService :DictionarysService
  ) {
    this.initObject();
  }

  ngOnInit() {
    this.initDictionaryZTree();
    //初始化修改表单
    this.initUpdateFrom();
    this.pushPage();
  }

  initObject(){
    this.dic = new Dictionary();
    this.buildForm();

  }

  /**
   * 面包屑导航
   */
  pushPage(){
    let path = new Path("数据字典","");
    this.pageSubject.pushPage("数据字典","修改",path);
  }


  /**
   * 通过id查询
   */
  initUpdateFrom() {
    //获取路由参数
    let id = this.route.snapshot.params["id"];
    this.dicService.getDDById(id).subscribe(
      result => this.responseUtil.success(result, this.processGetResult),
      error => this.responseUtil.error(error)
    );
  }
  /**
   * id查询成功后调用
   * @param json
   */
  private processGetResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dic = result.data;
      this.dicForm.patchValue(this.dic);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }
  /**
   * 构造表单
   */
  buildForm(): void {
    this.dicForm = this.fb.group({
      'pId': [this.dic.pId],
      'pName': [this.dic.pName],
      'id': [this.dic.id],
      'display': [this.dic.display, [
        Validators.required,
        Validators.maxLength(30)
      ]],
      'code': [this.dic.code, [
        Validators.required,
        Validators.pattern(/^[A-Z0-9_]+$/)
      ]],
      'value': [this.dic.value, [
        Validators.pattern(/^[A-Za-z0-9_]+$/)
      ]],

      'orderNum': [this.dic.orderNum, [
        Validators.required,
        Validators.maxLength(3),
        Validators.pattern(/^[\d]{0,}$/)
      ]],
      'describe': [this.dic.describe, [
        Validators.maxLength(30)
      ]],
      'isUse': [this.dic.isUse, [
        Validators.required,
        Validators.maxLength(1)
      ]]
    });

    this.dicForm.valueChanges.subscribe(
      data => this.onValueChanged(data)
    );
    this.onValueChanged();
  }


  /**
   * 值变化监听
   * @param data
   */
  onValueChanged(data?: any) {
    if (!this.dicForm) {
      return;
    }
    const form = this.dicForm;
    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      const control = form.get(field);
      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

  /**
   * 校验字段
   * @type {{name: string; code: string}}
   */
  formErrors = {
    'pName': '',
    'code': '',
    'value': '',
    'orderNum': '',
    'describe': '',
    'isUse': '',
    'display':''
  };

  /**
   * 校验提示信息
   * @type {{name: {required: string; maxlength: string}; code: {required: string; maxlength: string; pattern: string}}}
   */
  validationMessages = {
    'display': {
      'required': '字典名不能为空',
      'maxlength': '长度不能超过30',
    },
    'pName': {
      'maxlength': '长度不能超过30',
    },
    'code': {
      'required': '编码不能为空',
      'pattern': '只能由大写字母、数字组成'
    },
    'value': {
      'pattern': '必须为字母或数字或空'
    },
    'orderNum': {
      'required': '序号不能为空',
      'pattern': '只能是数字' ,
      'maxlength': '长度不能超过3'
    },
    'describe': {
      'maxlength': '长度不能超过30',
    }
  };

  onSubmit(){
    this.dic = this.dicForm.value;

    this.dicService.editDD(this.dic).subscribe(
      result =>this.responseUtil.success(result,this.processUpdateResult),
      message=>this.responseUtil.error(message)
    );
  }
  /**
   * 修改成功后调用
   * @param json
   */
  private processUpdateResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.success(result.message, () => this.cancelDicEdit());
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 取消添加菜单
   */
  cancelDicEdit(){
    this.router.navigate(['..'],{relativeTo :this.route});
  }

  /**
   * 初始化菜单树
   */
  initDictionaryZTree() {
    this.dicService.treeDD().subscribe(
      result => this.responseUtil.success(result, this.processMenuTreeResult),
      message => this.responseUtil.error(message)
    );
  }
  private processMenuTreeResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.initDictionaryTree(result.data);
      this.initPName(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }
  initDictionaryTree(dics) {
    //初始化菜单树
    let setting = {
      callback: {
        onClick: this.clickTree
      },
      data: {
        simpleData: {
          enable: true,
          idKey: "id",
          pIdKey: "pId",
          rootPId: 0
        }
      }

    };
    //把树放进页面
    this.treeObj = $.fn.zTree.init($("#dic_update_ZTree"), setting, dics);
  }
  clickTree = (event, treeId, treeNode) => {
    if(treeNode.id == this.dicForm.value.pId){
      let nodes = this.treeObj.getSelectedNodes();
      if (nodes.length>0) {
        this.treeObj.cancelSelectedNode(nodes[0]);
      }
      this.dic = this.dicForm.value;
      this.dic.pId = '';
      this.dic.pName = '';
      this.dicForm.patchValue(this.dic);
    }else{
      this.dic = this.dicForm.value;
      this.dic.pId = treeNode.id;
      this.dic.pName = treeNode.name;
      this.dicForm.patchValue(this.dic);
    }
  }

  initPName = (dics) =>{
    dics.forEach((dict, i) => {
      if(dict.id == this.route.snapshot.params["id"]){
        this.pId = dict.pId;
        return false;
      }
    });
    dics.forEach((dict, i) => {
      if(dict.id == this.pId ){
        this.dic = this.dicForm.value;
        // this.menu.pId = menu.id;
        this.dic.pName = dict.name;
        this.dicForm.patchValue(this.dic);
        return false;
      }
    });
  };
}
